<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!--      <el-form-item label="菜品分类id" prop="categoryId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.categoryId"-->
      <!--          placeholder="请输入菜品分类id"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="套餐名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入套餐名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="售卖状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择售卖状态" clearable>
          <el-option
            v-for="dict in dict.type.sc_dish_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="描述信息" prop="description">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.description"-->
      <!--          placeholder="请输入描述信息"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="商户id" prop="merchantId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.merchantId"-->
      <!--          placeholder="请输入商户id"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          plain-->
      <!--          icon="el-icon-plus"-->
      <!--          size="mini"-->
      <!--          @click="handleAdd"-->
      <!--          v-hasPermi="['system:setmeal:add']"-->
      <!--        >新增</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <!--        <el-button-->
        <!--          type="success"-->
        <!--          plain-->
        <!--          icon="el-icon-edit"-->
        <!--          size="mini"-->
        <!--          :disabled="single"-->
        <!--          @click="handleUpdate"-->
        <!--          v-hasPermi="['system:setmeal:edit']"-->
        <!--        >修改</el-button>-->
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['system:setmeal:remove']"-->
      <!--        >删除</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['system:setmeal:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="setmealList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center">
        <!--        每页的序号都从1开始-->
        <!--        <template slot-scope="scope">-->
        <!--          {{ scope.$index + 1 }}-->
        <!--        </template>-->
        <!--        不间断序号-->
        <template slot-scope="scope">
          {{ (queryParams.page - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <!--      <el-table-column label="菜品分类id" align="center" prop="categoryId" />-->
      <el-table-column label="套餐名称" align="center" prop="name"/>
      <el-table-column label="套餐价格" align="center" prop="price"/>
      <el-table-column label="售卖状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sc_dish_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="描述信息" align="center" prop="description"/>
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="商户id" align="center" prop="merchantId" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:setmeal:edit']"
          >修改
          </el-button>
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--            v-hasPermi="['system:setmeal:remove']"-->
          <!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 修改套餐对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="590px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!--        <el-form-item label="菜品分类id" prop="categoryId">-->
        <!--          <el-input v-model="form.categoryId" placeholder="请输入菜品分类id" />-->
        <!--        </el-form-item>-->
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入套餐名称" disabled/>
        </el-form-item>
        <el-form-item label="套餐价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入套餐价格"/>
        </el-form-item>
        <el-form-item label="售卖状态" prop="status">
          <el-tooltip content="售卖状态和菜品分类中的分类状态同步" placement="top">
            <el-select v-model="form.status" disabled>
              <el-option
                v-for="dict in dict.type.sc_dish_status"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-tooltip>
        </el-form-item>

        <el-form-item label="描述信息" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述信息"/>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <image-upload v-model="form.image"/>
        </el-form-item>

        <el-divider content-position="center">套餐菜品</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddScSetmealDish">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteScSetmealDish">删除
            </el-button>
          </el-col>
        </el-row>
        <el-table :data="setmealDishes" :row-class-name="rowScSetmealDishIndex"
                  @selection-change="handleScSetmealDishSelectionChange" ref="scSetmealDish">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="菜品名称" prop="name" width="150">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.name"
                placeholder="请选择菜品名称"
                filterable
                clearable
                @change="handlePriceChange(scope.row)"
              >
                <el-option
                  v-for="dish in dishList"
                  :key="dish.id"
                  :label="dish.name"
                  :value="dish.name"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="菜品价格" prop="totalPrice" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.totalPrice"
                placeholder="菜品总价"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="菜品份数" prop="copies" width="150">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.copies"
                :min="1"
                :precision="0"
                :step="1" style="width: 135px;"
                @change="handleCopiesChange(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listSetmeal, getSetmeal, delSetmeal, updateSetmeal} from "@/api/smartcanteen/setmeal";
import {listDish} from "@/api/smartcanteen/dish";

export default {
  name: "Setmeal",
  dicts: ['sc_dish_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedScSetmealDish: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 套餐表格数据
      setmealList: [],
      // 菜品表格数据
      dishList: [],
      // 套餐菜品关系表格数据
      setmealDishes: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        categoryId: null,
        name: null,
        price: null,
        status: null,
        description: null,
        image: null,
        merchantId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        price: [
          {required: true, message: "套餐价格不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询套餐列表 */
    getList() {
      this.loading = true;
      listSetmeal(this.queryParams).then(response => {
        this.setmealList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 查询菜品列表 */
    getDishList() {
      listDish({page: 1, pageSize: 100}).then(response => {
        this.dishList = response.data.records;
      });
    },
    // 根据菜品名称自动填充价格
    handlePriceChange(row) {
      if (row.name) {
        const selectedDish = this.dishList.find(dish => dish.name === row.name);
        if (selectedDish) {
          row.dishId = selectedDish.id; // 设置 dishId
          row.price = selectedDish.price; // 自动填充单价
          row.totalPrice = row.price * row.copies; // 计算总价
        } else {
          row.dishId = null; // 如果未找到对应菜品，清空 dishId
          row.price = null; // 如果未找到对应菜品，清空单价
          row.totalPrice = null; // 清空总价
        }
      } else {
        row.dishId = null; // 如果菜品名称为空，清空 dishId
        row.price = null; // 如果菜品名称为空，清空单价
        row.totalPrice = null; // 清空总价
      }
      this.updateSetmealPrice(); // 更新套餐总价
    },
    // 根据份数变化计算总价
    handleCopiesChange(row) {
      if (row.price) {
        row.totalPrice = row.price * row.copies; // 计算总价
      } else {
        row.totalPrice = null; // 如果单价为空，清空总价
      }
      this.updateSetmealPrice(); // 更新套餐总价
    },
    updateSetmealPrice() {
      if (this.setmealDishes.length > 0) {
        this.form.price = this.setmealDishes.reduce((total, dish) => {
          return total + (dish.totalPrice || 0);
        }, 0);
      } else {
        this.form.price = null; // 如果没有菜品，清空套餐总价
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        categoryId: null,
        name: null,
        price: null,
        status: 1,
        description: null,
        image: null,
        merchantId: null,
        createTime: null,
        updateTime: null,
        createUser: null,
        updateUser: null
      };
      this.setmealDishes = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加套餐";
      this.updateSetmealPrice(); // 更新套餐总价
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getDishList();
      const id = row.id || this.ids;
      getSetmeal(id).then(response => {
        this.form = response.data;
        this.setmealDishes = response.data.setmealDishes.map(dish => ({
          dishId: dish.dishId,
          name: dish.name,
          price: dish.price, // 确保 price 字段存在
          copies: dish.copies, // 确保 copies 字段存在
          totalPrice: dish.price * dish.copies // 计算 totalPrice
        }));
        this.updateSetmealPrice(); // 更新套餐总价
        this.open = true;
        this.title = "修改套餐";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.setmealDishes = this.setmealDishes;
          if (this.form.id != null) {
            updateSetmeal(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSetmeal(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除套餐编号为"' + ids + '"的数据项？').then(function () {
        return delSetmeal(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 套餐菜品关系序号 */
    rowScSetmealDishIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 套餐菜品关系添加按钮操作 */
    handleAddScSetmealDish() {
      if (!this.setmealDishes) {
        this.setmealDishes = [];  // 如果未定义，初始化为空数组
      }
      let obj = {
        dishId: null,
        name: "",
        price: null,
        copies: 1,
        totalPrice: null // 初始化总价为 null
      };
      this.setmealDishes.push(obj);
      this.updateSetmealPrice(); // 更新套餐总价
    },
    /** 套餐菜品关系删除按钮操作 */
    handleDeleteScSetmealDish() {
      if (this.checkedScSetmealDish.length === 0) {
        this.$modal.msgError("请先选择要删除的套餐菜品关系数据");
      } else {
        const setmealDishes = this.setmealDishes;
        const checkedScSetmealDish = this.checkedScSetmealDish;
        this.setmealDishes = setmealDishes.filter(function (item) {
          return checkedScSetmealDish.indexOf(item.index) === -1
        });
        this.updateSetmealPrice(); // 更新套餐总价
      }
    },
    /** 复选框选中数据 */
    handleScSetmealDishSelectionChange(selection) {
      this.checkedScSetmealDish = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/setmeal/export', {
        ...this.queryParams
      }, `setmeal_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
